package com.blog.service.impl;

import com.blog.VO.ArticleDetail;
import com.blog.VO.ArticleWithCategory;
import com.blog.VO.SidebarVO;
import com.blog.dto.ArticleCardDTO;
import com.blog.dto.ArticleDTO;
import com.blog.dto.Result;
import com.blog.entity.Article;
import com.blog.entity.Tag;
import com.blog.entity.Users;
import com.blog.mapper.*;
import com.blog.service.ArticleService;
import com.blog.utils.ArticleSearchUtils;
import com.blog.utils.JwtTokenProvider;
import com.blog.utils.MinioUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.blog.utils.MarkdownUtil.Markdown;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private TagMapper tagMapper;
    @Resource
    private BlogTagMapper blogTagMapper;

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private ArticleSearchUtils articleSearchUtils;
    @Resource
    private KafkaProducerServiceImpl kafkaProducerService;
    @Override
    @Transactional
    public void addArticle(ArticleDTO articledto) {
        try {
            kafkaProducerService.addArticleandEs(articledto);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public Result getArticle(Integer articleId) {
        Article article = articleMapper.getarticlebyid(articleId);
        List<Tag> tags = blogTagMapper.get_tag(articleId);
        Users users = usersMapper.findById(article.getAuthorId());

        ArticleDetail articleDetail = ArticleDetail.builder()
                .article(article)
                .tags(tags)
                .username(users.getNickname())
                .avatar(users.getAvatar())
                .categoryName(categoryMapper.getcategorybyId(article.getCategoryId()))
                .build();
        return Result.ok(articleDetail);
    }

    @Override
    public Result getarticlecards(Integer pageNum, Integer pageSize) {
        Integer total = articleMapper.get_article_counts();
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articles = articleMapper.getarticlecards();
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        List<ArticleCardDTO> articleCardDTOS = articles.stream()
                .map(article -> ArticleCardDTO.builder()
                        .Id(article.getId())          // 设置文章ID
                        .title(article.getTitle())                // 设置标题
                        .mainContent(Markdown(article.getContent()))       // 设置主要内容
                        .createTime(article.getCreateTime().toString()) // 设置创建时间（转字符串）
                        .categoryName(categoryMapper.getcategorybyId(article.getCategoryId())) // 通过分类ID获取分类名称
                        .author(article.getAuthor())              // 设置作者
                        .viewCount(article.getViewCount())        // 设置浏览量
                        .tags(blogTagMapper.get_tag(article.getId()))
                        .total(total)
                        .status(2)
                        .build()                                  // 构建 ArticleCardDTO 对象
                )
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", articleCardDTOS); // DTO 列表
        result.put("total", pageInfo.getTotal()); // 总记录数
        result.put("pageNum", pageInfo.getPageNum()); // 当前页
        result.put("pageSize", pageInfo.getPageSize()); // 每页大小
        return Result.ok(result);
    }

    @Override
    public Result get_sidebar() {
        SidebarVO sidebarVO = SidebarVO.builder()
                .articleCount(articleMapper.get_article_counts())
                .categoryCount(categoryMapper.get_category_counts())
                .tagCount(tagMapper.get_category_counts())
                .visitCount(articleMapper.get_article_view_counts())
                .categoryDetailVOlist(categoryMapper.selectArticlesWithCategory())
                .tagList(tagMapper.get_tag())
                .build();
        return Result.ok(sidebarVO);
    }

    @Override
    public Result uploadimages(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        long maxSize = 10 * 1024 * 1024; //允许上传的单个图片大小5MB
        if(file.getSize() > maxSize) {
            return Result.fail(500, "图片大小不能超过10MB", null);
        }
        if(extension == null || (!extension.equals("jpg") && !extension.equals("png") && !extension.equals("jpeg"))) {
            return Result.fail(500, "请上传图片", null);
        }
        String fileurl;
        try {
            fileurl = minioUtil.upload(file);
        } catch (Exception e) {
            Result.fail(500, "上传失败", null);
            throw new RuntimeException(e);
        }
        System.out.println("fileurl:" + fileurl);

        return Result.ok(fileurl);
    }


}
